package imgshare.controller;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import imgshare.common.api.CommonResult;
import imgshare.common.event.ServerAnnouncementCreatedEvent;
import imgshare.common.sse.SseEmitters;
import imgshare.model.Notification;
import imgshare.service.NotificationService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/notification")
public class NotificationController {

    @Autowired
    NotificationService notificationService;
    @Autowired
    SseEmitters emitters;
    private static final Log log = LogFactory.get();
    @Autowired
    private ApplicationEventPublisher eventPublisher;

    /**
     * 建立sse连接
     * @param userId
     * @return
     */
    @GetMapping(value = "/sse/connect/{userId}",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter createConnection(@PathVariable Integer userId) {
        return emitters.connect(userId);
    }

    @RequiresAuthentication
    @GetMapping("/sse/close/{userId}")
    public void closeConnection(@PathVariable Integer userId) {
        log.info("用户[{}]断开sse连接");
        emitters.get(userId).complete();
    }

    @RequiresAuthentication
    @GetMapping
    public CommonResult<List<Notification>> list(@RequestParam @NotNull Integer userId) {

        List<Notification> notificationList = notificationService.findByReceiverId(userId);
        return CommonResult.success(notificationList);
    }

    /**
     * 统计未读通知数量
     * @param userId
     * @return
     */
    @RequiresAuthentication
    @GetMapping("/count_unread")
    public CommonResult<Integer> countUnread(@RequestParam @NotNull Integer userId) {

        int unreadNum = notificationService.countUnreadNoticeByReceiverId(userId);
        return CommonResult.success(unreadNum);
    }

    /**
     * 创建系统公告，发送给所有用户
     * @param notification
     * @return
     */
    @RequiresRoles("admin")
    @PostMapping("/system_announcement_create")
    public CommonResult<?> createSystemAnnouncement(@RequestBody @Validated Notification notification) {
        notification.setType("system");
        notification.setCreatedTime(LocalDateTime.now());
        //-1代表所有用户
        notification.setReceiverId(-1);
        notificationService.create(notification);

        eventPublisher.publishEvent(new ServerAnnouncementCreatedEvent(this,notification));
        return CommonResult.success("创建成功");
    }

    /**
     * 更新为已读
     * @param notification
     * @return
     */
    @RequiresAuthentication
    @PostMapping("/update")
    public CommonResult<?> update(@RequestBody Notification notification) {
        notificationService.update(notification);
        return CommonResult.success();
    }

}
